<template>
  <div class="batch_detail">
    <div v-if="getDetailData" ref="headerRef" class="header">
      <div class="text">
        <div class="title">
          批次编号：{{ getDetailData.code }}
          <template v-if="getDetailData.type == 2">【物料】</template>
          <template v-else>【成品】</template>
        </div>
        <div class="sub_title">
          <p>创建人：{{ getDetailData.createEmp }}</p>
          <p>创建时间：{{ getDetailData.createTime }}</p>
        </div>
      </div>
      <div class="btn_group">
        <div class="download">
          <div class="btn_item">
            <HPlainButton :padding-right="12" @click="codeExportTxt">
              <el-icon>
                <Download />
              </el-icon>
              txt格式下载
            </HPlainButton>
          </div>
          <div class="btn_item">
            <HPlainButton :padding-right="12" @click="codeBatchExcel(1)">
              <el-icon>
                <Download />
              </el-icon>
              XLSX格式下载
            </HPlainButton>
            <p class="tips">适用于Excel版本2007以上</p>
          </div>
          <div class="btn_item">
            <HPlainButton :padding-right="12" @click="codeBatchExcel(2)">
              <el-icon>
                <Download />
              </el-icon>
              XLS格式下载
            </HPlainButton>
            <p class="tips">适用于Excel版本2003以上</p>
          </div>
          <div class="btn_item">
            <HPlainButton :padding-right="12" @click="codeBatchExcel(3)">
              <el-icon>
                <Download />
              </el-icon>
              CSV格式下载
            </HPlainButton>
            <p class="tips">适用于Excel版本2007以下</p>
          </div>
        </div>
        <div class="line"></div>
        <div class="del">
          <HPlainButton type="error" @click="deleCo">删除条码</HPlainButton>
        </div>
      </div>
    </div>
    <div class="line"></div>
    <div class="table_container" :style="tableContainerStyle">
      <div class="operate">
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量修改
              </el-dropdown-item>
              <el-dropdown-item @click="deleteAll">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="table">
        <el-table
          :border="true"
          stripe
          resizable
          :data="bathList"
          height="100%"
          width="100%"
          @selection-change="handleChange"
        >
          <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
          <el-table-column type="index" label="序号" width="50" fixed="left" :align="'center'" />
          <el-table-column show-overflow-tooltip prop="securityCode" label="条码" min-width="160" />
          <el-table-column
            show-overflow-tooltip
            prop="storeCode"
            label="仓储条码"
            min-width="160"
          />
          <el-table-column show-overflow-tooltip prop="city" label="产品/物料名称" width="250">
            <template #default="scope">
              {{ scope.row.brand }}&nbsp;{{ scope.row.goodsModel }}&nbsp;{{
                scope.row.goodsName
              }}&nbsp;{{ scope.row.goodsSpecName }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="registerTime" label="登记时间" width="180" />
          <el-table-column label="状态" width="90" fixed="right" :align="'center'">
            <template #default="scope">
              <div class="flex_justify_center">
                <HStatus v-if="scope.row.status === 3" type="info">已过保</HStatus>
                <HStatus v-if="scope.row.status === 2">质保中</HStatus>
                <HStatus v-if="scope.row.status === 1" type="info">未质保</HStatus>
                <HStatus v-if="scope.row.status === 4" type="error">已作废</HStatus>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="条码出入库状态" width="120" fixed="right" :align="'center'">
            <template #default="scope">
              <div class="flex_justify_center">
                <HStatus v-if="scope.row.storeStatus === 1" type="warning">未出入库</HStatus>
                <HStatus v-if="scope.row.storeStatus === 2" type="success">已入库</HStatus>
                <HStatus v-if="scope.row.storeStatus === 3" type="success">已出库</HStatus>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginDom"
          :list_total="total"
          @size-change="getPageList"
          @current-change="getPageList"
        />
      </div>
    </div>

    <!-- 批量修改弹窗 -->
    <h-dialog
      v-model="changeDialog"
      title="批量修改条码"
      :width="800"
      :loading="multipleUpdateLoading"
    >
      <div class="header" style="margin-bottom: 4px">
        条码数量：<span>{{ selecttion.length }}</span></div
      >
      <el-table :border="true" :data="[{ model: value1, spec: value2, warrantyDays: num }]">
        <el-table-column label="产品型号">
          <el-select
            v-model="value1"
            class="part"
            placeholder="型号"
            filterable
            clearable
            :loading="loading"
            remote-show-suffix
            :filter-method="remoteMethod"
            @change="changeSelect"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :value="item.id"
              :label="item.model"
              class="left12"
            />
          </el-select>
        </el-table-column>
        <el-table-column label="产品规格">
          <el-select
            v-model="value2"
            class="part"
            placeholder="规格"
            filterable
            clearable
            :loading="loading2"
            remote-show-suffix
            :filter-method="remoteMethod2"
          >
            <el-option
              v-for="item in options2"
              :key="item.id"
              :value="item.id"
              :label="item.name"
              class="left12"
            />
          </el-select>
        </el-table-column>
        <el-table-column label="质保周期">
          <el-input-number v-model.trim="num" class="num-inp" :min="1" />
        </el-table-column>
      </el-table>
      <template #footer>
        <HButton type="primary" is-modal @click="onSave">保存</HButton>
        <HButton is-modal @click="changeDialog = false">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, watch, CSSProperties, onUnmounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import moment from 'moment'
  import {
    codeBatchExportExcel,
    codeBatchExportTxt,
    getDetail,
    getbatchCodeList,
    deletebatchList,
    deleteCode,
    updateCodeGoods,
    productPageSelect,
    sparePageSelect,
    productSpecPageSelect,
    spareSpecPageSelect,
  } from '@/api/code'
  import _ from 'lodash'
  import { ArrowDown, CircleCheck, Delete, Download } from '@element-plus/icons-vue'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.snCode.batchDetail,
  })

  const headerRef = ref<HTMLDivElement | null>(null)
  const tableContainerStyle = ref<CSSProperties>({})
  const setTableContainerStyle = () => {
    tableContainerStyle.value.height = 'calc(100% - 37px - 44px)'
    if (headerRef.value) {
      tableContainerStyle.value.height = `calc(100% - 19px - ${headerRef.value.scrollHeight}px)`
    }
  }

  const tagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const value1 = ref(null)
  const value2 = ref(null)
  const num = ref(1)
  const total = ref(0)
  const paginDom = ref()
  const changeDialog = ref(false)
  const getDetailData = ref(null)
  const loading = ref(false)
  const loading2 = ref(false)
  const dataPage = ref({
    limit: 0,
    page: 0,
  })
  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val) => {
    selecttion.value = []
    val.forEach((item) => {
      selecttion.value.push({ id: item.id, tableType: item.tableType })
    })
  }
  const options = ref(null)
  const options2 = ref(null)
  // 批量修改
  const changeAll = () => {
    if (selecttion.value.length == 0) {
      ElMessageBox({
        title: '提示',
        message: '请选择要修改的条码',
        type: 'warning',
      })
      return
    }
    changeDialog.value = true
    remoteMethod('')
  }

  // 获取型号下拉选项的参数
  const getModelOptionsKeyword = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  const remoteMethod = _.throttle((val: string) => {
    if (getModelOptionsKeyword.value.name !== val) {
      getModelOptionsKeyword.value.name = val
      getModelOptions()
    }
  }, 500)

  /**
   * 获取型号下拉选项
   */
  const getModelOptions = async () => {
    loading.value = true
    if (getDetailData.value.type === 1) {
      const res = await productPageSelect(getModelOptionsKeyword.value)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
        loading.value = false
      } else {
        ElMessageBox({
          message: res.data.message,
          type: 'error',
          title: '提示',
        })
      }
    } else {
      const res = await sparePageSelect(getModelOptionsKeyword.value)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
        loading.value = false
      } else {
        ElMessageBox({
          message: res.data.message,
          type: 'error',
          title: '提示',
        })
      }
    }
  }
  const changeSelect = () => {
    options2.value = []
    remoteMethod2('')
  }

  // 获取规格下拉选项的请求参数
  const getSpecificationsOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  const remoteMethod2 = _.throttle((val: string) => {
    if (getSpecificationsOptionsParam.value.name !== val) {
      getSpecificationsOptionsParam.value.name = val
      getSpecificationsOptions()
    }
  }, 500)

  /**
   * 获取规格下拉选项
   */
  const getSpecificationsOptions = async () => {
    if (!value1.value) {
      return
    }
    loading2.value = true
    if (getDetailData.value.type === 1) {
      const res = await productSpecPageSelect(getSpecificationsOptionsParam.value, value1.value)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
        loading2.value = false
      } else {
        ElMessageBox({
          message: res.data.message,
          type: 'error',
          title: '提示',
        })
      }
    } else {
      const res = await spareSpecPageSelect(getSpecificationsOptionsParam.value, value1.value)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
        loading2.value = false
      } else {
        ElMessageBox({
          message: res.data.message,
          type: 'error',
          title: '提示',
        })
      }
    }
  }

  // 保存
  const multipleUpdateLoading = ref(false)
  const onSave = () => {
    multipleUpdateLoading.value = true
    let data = {
      codes: selecttion.value,
      goodsId: value1.value,
      goodsSpecId: value2.value,
      type: getDetailData.value.type,
      warrantyDay: num.value,
    }
    updateCodeGoods(data).then((res) => {
      multipleUpdateLoading.value = false
      if (res.data.code == 20000) {
        getDetailData.value = res.data.data.row
        ElMessage({
          message: res.data.message,
          type: 'success',
          plain: true,
          duration: 5000,
          showClose: true,
        })
        getDeta() // 详情
        getPageList() //条码列表
        changeDialog.value = false
      } else {
        ElMessageBox({
          message: res.data.message,
          type: 'error',
          title: '提示',
        })
      }
    })
  }
  // 批量删除
  const deleteAll = () => {
    if (selecttion.value.length == 0) {
      ElMessageBox({
        message: '请选择要删除的条码',
        type: 'warning',
        title: '提示',
      })
      return
    }
    ElMessageBox.confirm('确认删除选中条码吗?', '提示', {
      draggable: true,
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'error',
      autofocus: false,
    }).then(() => {
      deleteCode(selecttion.value).then((res) => {
        if (res.data.code == 20000) {
          ElMessage({
            message: res.data.message,
            type: 'success',
            plain: true,
            duration: 5000,
            showClose: true,
          })
          getPageList() //条码列表
        } else {
          ElMessageBox({
            title: '提示',
            message: res.data.message,
            type: 'error',
          })
        }
      })
    })
  }

  /**
   * 删除条码
   */
  const deleCo = () => {
    let isDeleteing = false
    ElMessageBox({
      title: '提示',
      message: isDeleteing ? '正在删除中... ...' : '是否删除该条码?',
      type: isDeleteing ? 'error' : 'warning',
      cancelButtonText: '否',
      showCancelButton: true,
      confirmButtonText: '是',
      beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action) && !isDeleteing) {
          done()
        }

        if (action === 'confirm') {
          isDeleteing = true
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          deletebatchList([getDetailData.value.id]).then((res) => {
            if (res.data.code === 20000) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                plain: true,
                duration: 5000,
                showClose: true,
              })
              tagsViewStore.delView(route.path)
              router.push({ path: '/code/new' })
            } else {
              ElMessageBox({
                title: '提示',
                message: res.data.message,
                type: 'error',
              })
            }
            instance.confirmButtonLoading = false
            done()
          })
        }
      },
    })
  }
  const bathList = ref(null)
  const loadingShow = ref(true)
  // 详情
  const getDeta = async () => {
    const res = await getDetail(route.params.id)
    if (res.data.code == 20000) {
      getDetailData.value = res.data.data.row
    } else {
      ElMessageBox({
        title: '提示',
        autofocus: false,
        message: res.data.message,
        type: 'error',
      })
    }
  }
  //条码列表
  const getPageList = async () => {
    dataPage.value.limit = paginDom.value.size
    dataPage.value.page = paginDom.value.current
    const res = await getbatchCodeList(dataPage.value, route.params.id)
    total.value = parseInt(res.data.data.total) || 0
    bathList.value = res.data.data.rows
    loadingShow.value = false
  }
  // 下载Excel表格
  const codeBatchExcel = (val: number) => {
    // val======>  1-xlsx，2-xls，3-csv
    if (total.value != 0) {
      //没有数据时不能下载Excel
      codeBatchExportExcel(val, route.params.id).then((res) => {
        const url = window.URL.createObjectURL(
          new Blob([res.data], { type: val == 1 ? '.xlsx' : val == 2 ? '.xls' : '.csv' }),
        )
        const link = document.createElement('a')
        link.href = url
        link.download = `条码批次_${moment(new Date()).format('YYYYMMDD')}${
          val == 1 ? '.xlsx' : val == 2 ? '.xls' : '.csv'
        }`
        link.click()
      })
    }
  }
  // 下载txt
  const codeExportTxt = () => {
    if (total.value != 0) {
      //没有数据时不能下载Excel
      codeBatchExportTxt(route.params.id).then((res) => {
        const url = window.URL.createObjectURL(new Blob([res.data], { type: 'txt' }))
        const link = document.createElement('a')
        link.href = url
        link.download = `条码批次_${moment(new Date()).format('YYYYMMDD')}.txt`
        link.click()
      })
    }
  }

  watch(value1, (value) => {
    if (value) {
      getSpecificationsOptions()
    }
  })

  onMounted(async () => {
    await getDeta() // 详情
    await getPageList() //条码列表
    await getModelOptions() // 获取型号下拉选项
    await getSpecificationsOptions() // 获取规格下拉选项
    setTableContainerStyle()
    window.addEventListener('resize', setTableContainerStyle)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', setTableContainerStyle)
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
